package com.ycsj.goldmedalnewconcept.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flyco.animation.BaseAnimatorSet;
import com.flyco.dialog.listener.OnBtnLeftClickL;
import com.flyco.dialog.listener.OnBtnRightClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.iflytek.cloud.EvaluatorListener;
import com.iflytek.cloud.EvaluatorResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvaluator;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.activity.LoginActivity;
import com.ycsj.goldmedalnewconcept.adapter.LazyBaseFragment;
import com.ycsj.goldmedalnewconcept.bean.YxInfo.QUESTIONLISTBean;
import com.ycsj.goldmedalnewconcept.bean.YxInfo.QUESTIONLISTBean.DETAILLISTBean;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.NetConstant;
import com.ycsj.goldmedalnewconcept.iflytek.ise.Result;
import com.ycsj.goldmedalnewconcept.iflytek.ise.XmlResultParser;
import com.ycsj.goldmedalnewconcept.utils.NetworkUtils;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;
import com.ycsj.goldmedalnewconcept.utils.UiHelper;
import com.ycsj.goldmedalnewconcept.view.AutoSizeTextView;

import org.json.JSONObject;

import java.io.File;
import java.util.List;

public class WordsYxFragment extends LazyBaseFragment implements
		OnClickListener {

	// 页面控件
	// 顶部的图片
	private ImageView lvPic;

	// 收藏的线性布局
	private RelativeLayout rlCollect;

	// 收藏图片
	private ImageView lvCollect;

	// 音
	private AutoSizeTextView tvSound;

	// 播放单词语音的喇叭
	private ImageView lvLb;

	// 译,例的整个布局
	private LinearLayout ll_yi, ll_li;

	// 译
	private AutoSizeTextView tv_paraphrase;

	// 例
	private TextView tv_example;

	// 底部的播放,录音,加载,显示分数的布局
	private ImageView lvPlay, lvRecord;;
	
	private LinearLayout llLoading;
	private TextView tvScore;

	// 讯飞SDK对象
	private SpeechEvaluator mSpeechEvaluator;

	// 当前页面的位置
	private int pos;

	// 当前页面的数据
	private QUESTIONLISTBean info;

	// 当前的LessionId
	private String lessionId;

	// 帧动画对象
	private AnimationDrawable animationDrawable;
	private AnimationDrawable popAnimationDrawable;

	// 播放器对象
	private MediaPlayer mMediaPlayer;

	// 用于控制第一次点击播放状态,默认是没有录音文件的
	private boolean hasRecord = false;

	// 控制松手是否显示加载框的标记
	private boolean isShowDialog = true;

	/**
	 * 录音的弹框PopUpWinow相关
	 */
	private View view;
	private ImageView lvPopRecord;
	private PopupWindow popupWindow;

	/**
	 * 对外提供的生成该类对象的方法,不可单例
	 * 
	 * @return
	 */
	public static WordsYxFragment newInstance(QUESTIONLISTBean info, int pos,
			String lessionId) {

		WordsYxFragment wordsYxFragment = new WordsYxFragment();
		Log.i("test","新文件");
		Log.i("test","新文件");
		Log.i("test","新文件");
		Log.i("test","新文件");
		Log.i("test","新文件");

		// 通过arguments携带页面数据
		Bundle bundle = new Bundle();
		bundle.putSerializable("data", info);
		bundle.putInt("position", pos);
		bundle.putString("lessionId", lessionId);
		wordsYxFragment.setArguments(bundle);
		return wordsYxFragment;
	}

	@Override
	public void lazyInit(View view, Bundle savedInstanceState) {

		// 获取页面数据
		getIntentData();

		// 初始化控件
		initView(view);

		// 设置页面数据
		setData();

		// 配置讯飞SDK对象的参数
		setParams();

		// 设置点击事件
		initListener();

		// 注册广播
		initRegisterBroadCast();

	}

	@Override
	protected int getLayoutId() {
		return R.layout.fragmetn_wordis_yuxi;
	}

	@Override
	protected void init(View view, Bundle savedInstanceState) {
		super.init(view, savedInstanceState);
	}

	/**
	 * 获取携带的数据
	 */
	private void getIntentData() {
		info = (QUESTIONLISTBean) getArguments().getSerializable("data");
		pos = getArguments().getInt("position");
		lessionId = getArguments().getString("lessionId");
	}

	/**
	 * 初始化控件的方法
	 */
	private void initView(View view) {
		rlCollect = (RelativeLayout) view.findViewById(R.id.rl_collect);
		lvPic = (ImageView) view.findViewById(R.id.iv_pic);
		lvCollect = (ImageView) view.findViewById(R.id.iv_collect);
		tvSound = (AutoSizeTextView) view.findViewById(R.id.tv_soundmark);
		tv_paraphrase = (AutoSizeTextView) view
				.findViewById(R.id.tv_paraphrase);
		tv_example = (TextView) view.findViewById(R.id.tv_example);
		lvLb = (ImageView) view.findViewById(R.id.lv_phonetic);
		ll_yi = (LinearLayout) view.findViewById(R.id.ll_yi);
		ll_li = (LinearLayout) view.findViewById(R.id.ll_li);
		llLoading = (LinearLayout) view.findViewById(R.id.ll_loading);
		tvScore = (TextView) view.findViewById(R.id.tv_score);
		lvPlay = (ImageView) view.findViewById(R.id.lv_play);
		lvRecord = (ImageView) view.findViewById(R.id.lv_record);
		tvScore.setVisibility(View.INVISIBLE);
		llLoading.setVisibility(View.INVISIBLE);
	}

	/**
	 * 设置页面数据的方法
	 */
	private void setData() {
		if (null != info) {
			List<DETAILLISTBean> datas = info.DETAIL_LIST;
			// 设置收藏的图片状态

			// 设置顶部图片,取集合的第一个元素
			Picasso.with(getActivity()).load(datas.get(1).DETAIL_CONTENT)
					.into(lvPic);

			// 设置音,取集合的第三个元素
			tvSound.setText(datas.get(3).DETAIL_CONTENT);

			// 设置译,取集合的第第二个元
			tv_paraphrase.setText(datas.get(2).DETAIL_CONTENT);

			// 设置例
			tv_example.setText(datas.get(4).DETAIL_CONTENT);

			// 设置是否已经收藏的图标
			if ("1".equals(info.FAVOR_STATUS)) {
				// 表示收藏过
				lvCollect.setImageResource(R.drawable.nav_collect_ed2x);
			} else {
				// 表示没有收藏
				lvCollect.setImageResource(R.drawable.nav_collect2x);
			}
		}
	}

	/**
	 * 设置点击事件的方法
	 */
	private void initListener() {
		rlCollect.setOnClickListener(this);
		ll_yi.setOnClickListener(this);
		ll_li.setOnClickListener(this);
		lvPic.setOnClickListener(this);
		lvLb.setOnClickListener(this);
		lvPlay.setOnClickListener(this);
		// 录音按钮的触摸事件
		lvRecord.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				switch (event.getAction()) {

				case MotionEvent.ACTION_DOWN:

					// 按下的时候重置状态
					isShowDialog = true;

					// 隐藏加载显示分数,下一步按钮
					llLoading.setVisibility(View.INVISIBLE);
					tvScore.setVisibility(View.INVISIBLE);

					// 按下的操作
					showRecordPop();

					// 同时开始录音并播放
					doRecordAction();

					break;

				case MotionEvent.ACTION_UP:

					// 停止评测方法
					if (null != mSpeechEvaluator) {
						mSpeechEvaluator.stopEvaluating();
					}

					// 松下的操作
					if (null != popupWindow && popupWindow.isShowing()) {
						popupWindow.dismiss();
					}

					// 松手的时候开始加载框转圈功能
					if (null != llLoading) {
						if (isShowDialog) {
							llLoading.setVisibility(View.VISIBLE);
						} else {
							llLoading.setVisibility(View.INVISIBLE);
						}
					}
				}

				return true;
			}
		});
	}

	/**
	 * 点击事件
	 * 
	 * @param v
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_yi:
		case R.id.ll_li:
			sycVisbility();
			// 例
			break;
		case R.id.rl_collect:
			// 收藏
			doCollectAction();
			break;
		case R.id.iv_pic:
			// 顶部图片的点击事件
			doTopImageAction();
			break;
		case R.id.lv_phonetic:
			// 喇叭的点击事件
			doLbAction();
			break;
		case R.id.lv_play:
			// 底部的播放按钮
			doBottomPlayAction();
			break;
		default:
			break;
		}
	}

	/**
	 * 点击收藏的操作
	 */
	private void doCollectAction() {
		if (TextUtils.isEmpty(SPUtils.getString(getActivity(), "account"))) {
			// 如果没有登录,跳转到登录界面
			// 没有登录弹出对话框提示登录
			showHintLoginPop();
		} else {
			// 请求服务器进行收藏和取消收藏的操作
			if ("1".equals(info.FAVOR_STATUS)) {
				// 表示已经收藏过,请求未收藏接口
				httpCancelCollect();
			} else {
				// 表示没有收藏过,请求收藏接口
				httpCollect();
			}

		}
	}

	/**
	 * 收藏接口
	 */
	private void httpCollect() {
		HttpUtils httpUtils = new HttpUtils();
		httpUtils.configCurrentHttpCacheExpiry(1000);
		httpUtils.send(
				HttpMethod.GET,
				NetConstant.USERFAVOR
						+ "/SaveUserQuestion.aspx?account="
						+ SPUtils.getString(getActivity(),
								ConfigConstant.USERNAME) + "&lessonid="
						+ lessionId + "&questionid=" + info.QUESTION_ID
						+ "&exam_type=3", new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// 请求收藏成功
						String json = responseInfo.result;
						Log.i("test", "请求收藏请求的结果是:" + json);
						try {
							JSONObject jsonObject = new JSONObject(json);
							String result = jsonObject.getString("resulttype");
							if ("true".equals(result)) {
								info.FAVOR_STATUS = "1";
								// 请求收藏成功
								getActivity().runOnUiThread(new Runnable() {
									public void run() {
										// 更新UI
										UiHelper.toast(getActivity(), "收藏成功");
										lvCollect
												.setImageResource(R.drawable.nav_collect_ed2x);
									}
								});
							} else {
								getActivity().runOnUiThread(new Runnable() {
									public void run() {
										// 更新UI
										UiHelper.toast(getActivity(), "收藏失败");
									}
								});
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// 请求收藏失败
						getActivity().runOnUiThread(new Runnable() {
							public void run() {
								if (null != llLoading) {
									llLoading.setVisibility(View.GONE);
									UiHelper.toast(getActivity(), "网络错误");
								}
							}
						});
					}
				});
	}

	/**
	 * 取消收藏接口
	 */
	private void httpCancelCollect() {
		HttpUtils httpUtils = new HttpUtils();
		httpUtils.configCurrentHttpCacheExpiry(1000);
		httpUtils.send(
				HttpMethod.GET,
				NetConstant.USERFAVOR
						+ "/CancelUserQuestion.aspx?account="
						+ SPUtils.getString(getActivity(),
								ConfigConstant.USERNAME) + "&lessonid="
						+ lessionId + "&questionid=" + info.QUESTION_ID
						+ "&exam_type=3", new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// 请求成功
						String json = responseInfo.result;
						Log.i("test", "取消收藏请求的结果是:" + json);
						try {
							JSONObject jsonObject = new JSONObject(json);
							String result = jsonObject.getString("resulttype");
							if ("true".equals(result)) {
								info.FAVOR_STATUS = "0";
								// 取消收藏成功
								getActivity().runOnUiThread(new Runnable() {
									public void run() {
										// 更新UI
										UiHelper.toast(getActivity(), "取消收藏成功");
										lvCollect
												.setImageResource(R.drawable.nav_collect2x);
									}
								});
							} else {
								getActivity().runOnUiThread(new Runnable() {
									public void run() {
										// 更新UI
										UiHelper.toast(getActivity(), "取消收藏失败");
									}
								});
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// 请求收藏失败
						getActivity().runOnUiThread(new Runnable() {
							public void run() {
								if (null != llLoading) {
									llLoading.setVisibility(View.GONE);
									UiHelper.toast(getActivity(), "网络错误");
								}
							}
						});
					}
				});
	}

	private BaseAnimatorSet bas_in;
	private BaseAnimatorSet bas_out;

	public void setBasIn(BaseAnimatorSet bas_in) {
		this.bas_in = bas_in;
	}

	public void setBasOut(BaseAnimatorSet bas_out) {
		this.bas_out = bas_out;
	}

	/**
	 * 提示登录的Dialog
	 */
	private void showHintLoginPop() {
		final NormalDialog dialog = new NormalDialog(getActivity());
		dialog.content("请先完成登陆后再进行收藏").btnText("登录", "取消")
				.style(NormalDialog.STYLE_TWO)//
				.titleTextSize(23).showAnim(bas_in).dismissAnim(bas_out).show();

		dialog.setCanceledOnTouchOutside(false);

		dialog.setOnBtnLeftClickL(new OnBtnLeftClickL() {

			@Override
			public void onBtnLeftClick() {

				if (null != dialog) {
					dialog.dismiss();
				}
				startActivity(new Intent(getActivity(), LoginActivity.class));
			}
		});

		dialog.setOnBtnRightClickL(new OnBtnRightClickL() {

			@Override
			public void onBtnRightClick() {
				if (null != dialog) {
					dialog.dismiss();
				}
			}
		});
	}

	/**
	 * 底部的播放按钮的点击事件
	 */
	private void doBottomPlayAction() {
		// 获取录音文件的地址
		// if (hasRecord) {

		if (!TextUtils.isEmpty(getAmrPath(pos))) {

			// 停止动画
			if (null != animationDrawable) {
				animationDrawable.stop();
			}
			// 恢复顶部喇叭的图标
			lvLb.setImageResource(R.drawable.lb);

			// 创建音频播放对象
			if (mMediaPlayer != null) {
				mMediaPlayer.release();
				mMediaPlayer = new MediaPlayer();
			} else {
				mMediaPlayer = new MediaPlayer();
			}
			// 设置完成播放的监听
			mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {

					// 改变图标
					lvPlay.setImageResource(R.drawable.playcloze);
					if (mMediaPlayer != null) {
						mMediaPlayer.release();
					}

				}
			});

			// 播放录制的本地音频
			try {
				// if (TextUtils.isEmpty(getAmrPath(pos))) {
				// UiHelper.toast(getActivity(), "请先录音");
				// return;
				// }
				mMediaPlayer.setDataSource(getAmrPath(pos));

				mMediaPlayer.prepareAsync();

				mMediaPlayer
						.setOnPreparedListener(new OnPreparedListener() {
							@Override
							public void onPrepared(MediaPlayer mp) {
								mMediaPlayer.start();
								// 改变图标
								lvPlay.setImageResource(R.drawable.stopcloze);
							}
						});

			} catch (Exception e) {
				Log.i("test", e.toString());
			}
		} else {
			// 无存放的音频文件
			UiHelper.toast(getActivity(), "请先录音");
			return;
		}
	}

	/**
	 * 点击喇叭播放音频文件的方法
	 */
	private void doLbAction() {
		
		if(NetworkUtils.isAvailable(getActivity())){
			
		try {
			// 给顶部的图片设置帧动画
			lvLb.setImageResource(R.drawable.lv_frame_b);

			// 获取帧动画对象
			animationDrawable = (AnimationDrawable) lvLb.getDrawable();

			// 播放内容音乐
			if (null == mMediaPlayer) {
				// 没有播放对象
				// 如果播放器为null,就创建一个播放器
				mMediaPlayer = new MediaPlayer();

			} else {
				// 有播放对象
				mMediaPlayer.release();
				mMediaPlayer = new MediaPlayer();
			}

			mMediaPlayer.setDataSource(info.DETAIL_LIST.get(0).DETAIL_CONTENT);

			// 恢复底部的播放按钮的状态
			lvPlay.setImageResource(R.drawable.playcloze);
			
		
			
			// 设置准备监听
			mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {

				@Override
				public void onPrepared(MediaPlayer mp) {
					// 开始播放
					mMediaPlayer.start();
					// 执行帧动画
					if (null != animationDrawable) {
						animationDrawable.start();
					}
				}
			});

			// 同步完成
			mMediaPlayer.prepareAsync();

			// 设置播放监听
			mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					// 结束顶部的ImageView帧动画
					if (null != animationDrawable) {
						animationDrawable.stop();
					}

					// 恢复小喇叭的显示图标
					lvLb.setImageResource(R.drawable.lb);

					if (mMediaPlayer != null) {
						mMediaPlayer.release();
					}
				}
			});

		} catch (Exception e) {
			
			Log.i("test", e.toString());
			
		}
		}else{
			UiHelper.toast(getActivity(), "网络无响应，请检查网络连接");
		}
	}

	/**
	 * 顶部图片的点击事件
	 */
	private void doTopImageAction() {
		ObjectAnimator scaleX = ObjectAnimator.ofFloat(lvPic, "scaleX", 1f,
				0.5f, 1f);
		ObjectAnimator scaleY = ObjectAnimator.ofFloat(lvPic, "scaleY", 1f,
				0.5f, 1f);
		AnimatorSet animSet = new AnimatorSet();
		animSet.play(scaleX).with(scaleY);
		animSet.setDuration(1000);
		animSet.start();

		// 结束动画
		if (null != animationDrawable) {
			animationDrawable.stop();
		}

		// 重新设定喇叭的状态值
		if (null != lvLb) {
			lvLb.setImageResource(R.drawable.lb);
		}

		// 播放音频
		if (null == mMediaPlayer) {
			// 没有播放对象
			// 如果播放器为null,就创建一个播放器
			mMediaPlayer = new MediaPlayer();
		} else {
			// 有播放对象
			mMediaPlayer.release();
			mMediaPlayer = new MediaPlayer();
		}

		// 恢复底部的播放按钮的状态
		lvPlay.setImageResource(R.drawable.playcloze);

		// 播放单词的网络录音
		try {
			mMediaPlayer.setDataSource(info.DETAIL_LIST.get(0).DETAIL_CONTENT);

			mMediaPlayer.prepareAsync();

			mMediaPlayer
					.setOnPreparedListener(new OnPreparedListener() {
						@Override
						public void onPrepared(MediaPlayer mp) {
							mMediaPlayer.start();
							
							
							
						}
					});

		} catch (Exception e) {
			Log.i("test", e.toString());
		}
	}

	/**
	 * 同步显示状态的方法
	 */
	private void sycVisbility() {
		if (tv_paraphrase.getVisibility() != View.VISIBLE) {
			tv_paraphrase.setVisibility(View.VISIBLE);
		}
		if (tv_example.getVisibility() != View.VISIBLE) {
			tv_example.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 设置讯飞语音录制对象的参数方法
	 */
	private void setParams() {

//		mSpeechEvaluator = SpeechEvaluator.createEvaluator(getActivity(), null);

		mSpeechEvaluator = SpeechEvaluator.createEvaluator(getActivity(),null);

		Log.d("test","run");
		// 设置评测语种
		mSpeechEvaluator.setParameter(SpeechConstant.LANGUAGE, "en_us");
		// 设置评测题型
		mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY, "read_word");

		// mSpeechEvaluator.setParameter(SpeechConstant.ISE_CATEGORY,
		// "read_sentence");// 句子
		// 设置试题编码类型
		mSpeechEvaluator.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
		// 设置前、后端点超时
		mSpeechEvaluator.setParameter(SpeechConstant.VAD_BOS, "5000");
		mSpeechEvaluator.setParameter(SpeechConstant.VAD_EOS, "1800");
		// 设置录音超时，设置成-1 则无超时限制
		mSpeechEvaluator.setParameter(SpeechConstant.KEY_SPEECH_TIMEOUT, "-1");
		// 设置结果等级，不同等级对应不同的详细程度
		mSpeechEvaluator.setParameter(SpeechConstant.RESULT_LEVEL, "complete");
		// 设置音频保存路径，保存音频格式支持pcm、wav，设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
		// 注：AUDIO_FORMAT参数语记需要更新版本才能生效
		mSpeechEvaluator.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");

		// 配置录音文件存放的位置
		// mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
		// Environment.getExternalStorageDirectory().getAbsolutePath()
		// + "/msc/" + "ice" + postion + ".wav");

	}

	/**
	 * 根据当前页面获取录音文件的路径的方法
	 * 
	 * @return
	 */
	private String getAmrPath(int postion) {
		File file = new File(
				getActivity().getExternalCacheDir().getAbsolutePath()
				+ "/msc/"
				+ "icewordsyx"
				+ lessionId
				+ postion
				+ ".wav");
		if(file.exists()){
			return file.getAbsolutePath();
		}else{
			return "";
		}
	}

	/**
	 * 弹出录音的PopUpwindow
	 */
	private void showRecordPop() {

		view = View.inflate(getActivity(), R.layout.pop_record, null);

		lvPopRecord = (ImageView) view.findViewById(R.id.lv_pop_record);
		// 给顶部的图片设置帧动画
		lvPopRecord.setImageResource(R.drawable.record_anim);

		// 获取帧动画对象
		popAnimationDrawable = (AnimationDrawable) lvPopRecord.getDrawable();

		// 开启帧动画
		popAnimationDrawable.start();

		popupWindow = new PopupWindow(view,
				WindowManager.LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.WRAP_CONTENT);

		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());

		popupWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				if (null != popAnimationDrawable) {
					popAnimationDrawable.stop();
				}
			}
		});
		popupWindow.showAtLocation(getActivity().getWindow().getDecorView(),
				Gravity.CENTER, 0, 0);
	}

	/**
	 * 语音评测的方法
	 */
	private void doRecordAction() {

		// 清空播放器的播放状态
		// 释放资源对象
		if (null != mMediaPlayer) {
			mMediaPlayer.release();
		}

		// 设置顶部喇叭的图片
		lvLb.setImageResource(R.drawable.lb);

		// 恢复底部的播放按钮的状态
		lvPlay.setImageResource(R.drawable.playcloze);

		// 停止动画
		if (null != animationDrawable) {
			animationDrawable.stop();
		}

		// 震动手机
		Vibrator vibrator = (Vibrator) getActivity().getSystemService(
				Service.VIBRATOR_SERVICE);
		vibrator.vibrate(500);

		if (mSpeechEvaluator == null) {
			return;
		}

		// 重新配置讯飞的录音存放位置
		mSpeechEvaluator.setParameter(SpeechConstant.ISE_AUDIO_PATH,
				getActivity().getExternalCacheDir().getAbsolutePath()
//				Environment.getExternalStorageDirectory().getAbsolutePath()
						+ "/msc/" + "icewordsyx" + lessionId + pos + ".wav");
		// 开启评测功能
		mSpeechEvaluator.startEvaluating("[word]\r\n" + info.QUESTION_CONTENT,
				null, new EvaluatorListener() {

					// volume音量值0~30，data音频数据
					@Override
					public void onVolumeChanged(int volume, byte[] data) {

					}

					// 结果回调，评测过程中可能会多次调用该方法，isLast为true则为最后结果
					@SuppressWarnings({ "static-access", "static-access" })
					@Override
					public void onResult(final EvaluatorResult result,
							boolean isLast) {
						if (isLast) {
							getActivity().runOnUiThread(new Runnable() {

								@Override
								public void run() {
									StringBuilder builder = new StringBuilder();
									builder.append(result.getResultString());

									XmlResultParser resultParser = new XmlResultParser();
									Result result1 = resultParser.parse(result
											.getResultString());

									// 处理乱读的问题
									if (!TextUtils.isEmpty(builder)) {
										float a = result1.total_score;
										float b = (float) (Math.round(a * 10)) / 10;

										// 更改是否继续显示弹框的标识
										isShowDialog = false;

										// 更改录音文件状态证明已经录音
										// hasRecord = true;

										if (null != popupWindow
												&& popupWindow.isShowing()) {
											popupWindow.dismiss();
										}

										llLoading.setVisibility(View.INVISIBLE);
										tvScore.setVisibility(View.VISIBLE);
										tvScore.setText(b + " 分");

										// 播放科大讯飞的评分语音
										AssetManager assetManager = getActivity()
												.getAssets();
										if (mMediaPlayer != null) {
											mMediaPlayer.release();
											mMediaPlayer = null;
											mMediaPlayer = new MediaPlayer();
										} else {
											mMediaPlayer = new MediaPlayer();
										}
										// 设置完成监听,主要作用是为了播放完成后让顶部的喇叭和底部左边的播放按钮变成可点击状态
										mMediaPlayer
												.setOnCompletionListener(new OnCompletionListener() {

													@Override
													public void onCompletion(
															MediaPlayer mp) {
														if (mMediaPlayer != null) {
															mMediaPlayer
																	.release();
															mMediaPlayer = null;
														}

														// 清除动画效果
														if (null != animationDrawable) {
															animationDrawable
																	.stop();
														}
														lvRecord.setImageResource(R.drawable.recordcloze);
													}
												});

										try {
											AssetFileDescriptor fileDescriptor1 = assetManager
													.openFd("1.mp3");
											AssetFileDescriptor fileDescriptor2 = assetManager
													.openFd("2.mp3");
											AssetFileDescriptor fileDescriptor3 = assetManager
													.openFd("3.mp3");
											AssetFileDescriptor fileDescriptor4 = assetManager
													.openFd("4.mp3");
											AssetFileDescriptor fileDescriptor5 = assetManager
													.openFd("5.mp3");
											if (b < 1.0) {
												mMediaPlayer.setDataSource(
														fileDescriptor1
																.getFileDescriptor(),
														fileDescriptor1
																.getStartOffset(),
														fileDescriptor1
																.getLength());
											} else if (b >= 1.0 && b < 2.0) {
												mMediaPlayer.setDataSource(
														fileDescriptor2
																.getFileDescriptor(),
														fileDescriptor2
																.getStartOffset(),
														fileDescriptor2
																.getLength());
											} else if (b >= 2.0 && b < 3.0) {
												mMediaPlayer.setDataSource(
														fileDescriptor3
																.getFileDescriptor(),
														fileDescriptor3
																.getStartOffset(),
														fileDescriptor3
																.getLength());
											} else if (b >= 3.0 && b < 4.0) {
												mMediaPlayer.setDataSource(
														fileDescriptor4
																.getFileDescriptor(),
														fileDescriptor4
																.getStartOffset(),
														fileDescriptor4
																.getLength());
											} else if (b >= 4.0 && b <= 5.0) {
												mMediaPlayer.setDataSource(
														fileDescriptor5
																.getFileDescriptor(),
														fileDescriptor5
																.getStartOffset(),
														fileDescriptor5
																.getLength());
											}

											mMediaPlayer.prepare();
											mMediaPlayer.start();
										} catch (Exception e) {
											Log.i("test", e.toString());
										}
									}
								}
							});

						}
					}

					// 扩展接口，暂时没有回调
					@Override
					public void onEvent(int arg0, int arg1, int arg2,
							Bundle arg3) {

					}

					// 出错回调
					@Override
					public void onError(SpeechError error) {

						// 更新是否显示PopUpWindow
						isShowDialog = false;

						if (null != popupWindow && popupWindow.isShowing()) {
							popupWindow.dismiss();
						}

						if (null != llLoading) {
							llLoading.setVisibility(View.INVISIBLE);
						}

						if (null != tvScore) {
							tvScore.setVisibility(View.INVISIBLE);
						}

						UiHelper.toast(getActivity(), "请重新录音");

						Log.d("test",error.getErrorCode()+"");
					}

					// 说话结束回调
					@Override
					public void onEndOfSpeech() {
					}

					// 开始说话回调
					@Override
					public void onBeginOfSpeech() {

					}
				});
	}

	/**
	 * 注册页面切换停止播放的按钮,更改状态的广播
	 */
	private void initRegisterBroadCast() {
		IntentFilter filter = new IntentFilter(
				"com.ycsj.goldmedalnewconcept.sycstate");
		getActivity().registerReceiver(new MyReceiver(), filter);
	}

	/**
	 * 广播接受者
	 */
	class MyReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			// 释放资源对象
			if (mMediaPlayer != null) {
				mMediaPlayer.release();
			}

			// 停止动画资源
			if (null != animationDrawable) {
				animationDrawable.stop();
			}

			// 设置顶部喇叭的图片
			lvLb.setImageResource(R.drawable.lb);

			// 设置底部的播放按钮的图片
			lvPlay.setImageResource(R.drawable.playcloze);

			// 让PopUpWindow消失
			if (null != popupWindow && popupWindow.isShowing()) {
				popupWindow.dismiss();
			}

			// 更改是否录音的状态,只要页面滑动就认为没有录音
			// hasRecord = false;
		}
	}

}
